<template>
	<view class="pb-safe-area">
		<view class="p-4 flex flex-column grid-gap-4">
			<view class="bg-white rounded-4" v-if="WEBCONFIG?.to_shop_use && technicianInfo.work_shop_id">
				<view class="flex">
					<text class="flex-1 py-4 text-center h9" @tap="form.to_shop = 0" :class="!form.to_shop ? 'text-primary font-weight-600' : ''">预约</text>
					<text class="flex-1 py-4 text-center h9" @tap="form.to_shop = 1" :class="form.to_shop ? 'text-primary font-weight-600' : ''">到店</text>
				</view>
			</view>

			<view class="p-4 rounded-4 bg-white flex flex-center grid-gap-2"
				@tap="$page.open('/pages/user/address/list?event=' + $EventName.SELECT_ADDRESS)" v-if="!form.to_shop">
				<view class="flex-1 flex flex-column grid-gap-2">
					<view class="flex grid-gap-2">
						<text class="font-weight-600">{{ address.name }}</text>
						<text class="text-grey">{{ address.mobile }}</text>
					</view>
					<view>
						<text class="h9 text-placeholder mr-1" v-if="address.province">{{ address.province }}</text>
						<text class="h9 text-placeholder mr-1" v-if="address.city">{{ address.city }}</text>
						<text class="h9 text-placeholder mr-1" v-if="address.area">{{ address.area }}</text>
						<text class="h9 text-placeholder mr-1" v-if="address.street">{{ address.street }}</text>
						<text class="h9 text-placeholder">{{ address.address_detail }}</text>
					</view>
				</view>
				<uni-icons type="right"></uni-icons>
			</view>

			<view class="p-4 bg-white rounded-4 flex flex-column grid-gap-4">
				<view class="bg flex flex-column grid-gap-1">
					<view class="bg-white py-2" v-for="(item, index) in projects" :key="index">
						<x-project-item :project="item">
							<template #action>
								<x-input-number v-model="item.num" @change="valChange($event, index)"></x-input-number>
							</template>
						</x-project-item>
					</view>
				</view>

				<view class="flex flex-y-center flex-x-space-between">
					<text class="h9 text-placeholder">{{WebConfigStore.replaceIndustryPersonnelName('服务技师')}}</text>
					<view class="flex flex-center grid-gap-1">
						<image :src="technicianInfo.headimg" mode="scaleToFill" class="rounded-circle"
							style="width: 20px;height: 20px;" />
						<text class="h9">{{ technicianInfo.nickname }}</text>
					</view>
				</view>

				<view class="flex flex-y-center flex-x-space-between">
					<text class="h9 text-placeholder">服务时间</text>
					<view class="flex flex-center grid-gap-1" @tap="serviceTimeShow = true">
						<text class="h9" :class="[form.scheduling_id ? 'text-primary' : 'text-placeholder']">{{
							servive_time }}</text>
						<uni-icons type="right"></uni-icons>
					</view>
				</view>
			</view>

			<!-- 出行方式 -->
			<view class="bg-white p-4 rounded-4 flex flex-column grid-gap-4" v-if="!form.to_shop">
				<view class="flex flex-y-center flex-x-space-between" @tap="toChangeTravel()">
					<text class="font-weight-600">出行方式</text>
					<view class="flex flex-center grid-gap-1">
						<text class="text-warning-light-3" v-if="form.travel">{{ form.travel.name }}</text>
						<uni-icons type="right"></uni-icons>
					</view>
				</view>
				<view class="bg p-2 rounded-4 text-grey h10">{{ travel.text }}</view>
				<view class="flex flex-y-center flex-x-space-between">
					<text class="text-placeholder h9">车费</text>
					<x-money type="danger-light-3" weight="bold" size="8" :money="travel.price">
						<template #prefix>
							<text class="h10 text-danger-light-3">￥</text>
						</template>
					</x-money>
				</view>
			</view>

			<view class="bg-white p-4 rounded-4 flex flex-y-center flex-x-space-between" @tap="toSetCouponShow">
				<text class="text-placeholder h9">选择优惠券</text>
				<view class="flex flex-center grid-gap-1">
					<x-money type="warning-light-3" weight="bold" size="8" :money="coupon_price"
						v-if="coupon_price > 0">
						<template #prefix>
							<text class="h10 text-warning-light-3">￥</text>
						</template>
					</x-money>
					<uni-icons type="right"></uni-icons>
				</view>
			</view>

			<textarea class="bg-white rounded-4 p-4 bs-border-box w-100 min-vh-5" auto-height maxlength="255"
				placeholder="在此输入备注信息" v-model="form.remark"></textarea>

			<view class="bg-white rounded-4 flex flex-column grid-gap-6 px-4 py-6">
				<view class="flex flex-y-center flex-x-space-between">
					<text class="text-grey h9">基础服务合计,时长：{{ service_duration.basic_duration }}分钟</text>
					<x-money type="danger-light-3" weight="bold" size="8" :money="price.basic_price">
						<template #prefix>
							<text class="h10 text-danger-light-3">￥</text>
						</template>
					</x-money>
				</view>
				<view class="flex flex-y-center flex-x-space-between">
					<text class="text-grey h9">加钟服务合计,时长：{{ service_duration.overtime_duration }}分钟</text>
					<x-money type="danger-light-3" weight="bold" size="8" :money="price.overtime_price">
						<template #prefix>
							<text class="h10 text-danger-light-3">￥</text>
						</template>
					</x-money>
				</view>
				<view class="flex flex-y-center flex-x-space-between">
					<text class="text-grey h9">车费</text>
					<x-money type="danger-light-3" weight="bold" size="8" :money="travel.price">
						<template #prefix>
							<text class="h10 text-danger-light-3">￥</text>
						</template>
					</x-money>
				</view>
				<view class="flex flex-y-center flex-x-space-between" v-if="coupon_price > 0">
					<text class="text-grey h9">优惠券</text>
					<x-money type="danger-light-3" weight="bold" size="8" :money="coupon_price">
						<template #prefix>
							<text class="h10 text-danger-light-3">￥</text>
						</template>
					</x-money>
				</view>
			</view>
			<view class="bg-white p-4 rounded-4" v-if="travel.reach_time">
				<text class="text-grey h9">{{WebConfigStore.replaceIndustryPersonnelName('现在付款，技师约在')}}</text>
				<text class="text-danger-light-3 font-weight-600 h9">{{ travel.reach_time }}</text>
				<text class="text-grey h9">时间到达</text>
			</view>
			<x-refund-tips v-if="!form.to_shop" />
			<view class="flex flex-y-center flex-wrap" @tap="showAgreement()">
				<uni-icons type="circle-filled" v-if="form.agreement" color="var(--xl-primary)" />
				<uni-icons type="circle" v-else color="var(--xl-primary)" />
				<text class="h9 text-placeholder">请阅读并同意</text>
				<text class="text-primary h9"
					@tap="$page.open('/pages/article/content?alias=reservation_pay')">《服务订购协议》</text>
				<text class="text-primary h9" @tap="$page.open('/pages/article/content?alias=pay')">《支付协议》</text>
			</view>
		</view>
		<view class="x-tabbar-placeholder pb-safe-area">
			<view class="x-tabbar pb-safe-area" style="z-index:100;">
				<view class="flex-1 flex flex-center px-4">
					<view class="flex-1">
						<text class="text-placheolder h9"> 合计： </text>
						<x-money type="danger-light-3" weight="bold" size="8" :money="price_sum">
							<template #prefix>
								<text class="h10 text-danger-light-3">￥</text>
							</template>
						</x-money>
					</view>
					<button class="btn-primary-light-1 btn-round mx-0" size="mini" @tap="showPay()">立即下单</button>
				</view>
			</view>
		</view>

		<x-picker v-if="travels.length" v-model:show="travelShow" :columns="[travels]" keyName="name"
			confirm-color="var(--xl-primary)" @confirm="pickerPopup" />

		<x-select-servive-time v-model:show="serviceTimeShow" :serviceDuration="service_duration_sum"
			:technicianId="form.technician_id" @confirm="serviceTimePopup" />

		<x-my-coupon v-model:show="couponShow" :price="price.price" @confirm="couponPopup" />

		<x-pay v-model:show="payTypeShow" :orders-type="form.type" @confirm="payCallBack" :price="price_sum" />

		<x-loading v-if="loading" />
		<x-popup v-model="agreement" top="30vh">
			<view class="font-weight-600 text-center py-4">服务协议事项</view>
			<view class="p-10">
				<text class="h9 text-placeholder">为了更好地保障您的合法权益，请您阅读并同意</text>
				<text class="text-primary h9"
					@tap="$page.open('/pages/article/content?alias=reservation_pay')">《服务订购协议》</text>
				<text class="text-primary h9" @tap="$page.open('/pages/article/content?alias=pay')">《支付协议》</text>
				<view class="flex flex-y-center flex-wrap mt-10" @tap="agreementEnquire = !agreementEnquire">
					<uni-icons type="circle-filled" v-if="agreementEnquire" color="var(--xl-primary)" />
					<uni-icons type="circle" v-else color="var(--xl-primary)" />
					<text class="h9 text-placeholder">总是询问</text>
				</view>
			</view>
			<view class="p-4 flex grid-gap-4">
				<button class="flex-1 btn-round mx-0" @tap="hendleAgreement(false)">不同意</button>
				<button class="flex-1 btn-primary-light-1 btn-round mx-0" @tap="hendleAgreement(true)">同意</button>
			</view>
			<view class="pb-safe-area"></view>
		</x-popup>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, reactive, nextTick } from "vue";
import { $api, $message, $page, useStorage } from "@/utils";
import { onLoad, onUnload } from '@dcloudio/uni-app';
import { usePlatformStore,useWebConfigStore, useRefs } from "@/stores";
import { $ResponseCode, $EventName } from "@/utils/const/env";
import { usePay } from "@/utils/pay";
const PlatformStore = usePlatformStore();
const { PLATFORM } = useRefs(PlatformStore);
const WebConfigStore = useWebConfigStore();
const { WEBCONFIG } = useRefs(WebConfigStore);
const loading = ref(false);
const address = ref({
	name: '您还未设置默认地址',
	address_detail: '请选择地址',
});
const projects = ref([]);
const technicianInfo = ref({});
const servive_time = ref('选择服务时间');
const orders = ref({
	trade: ''
});
const agreement=ref(false);
const agreementEnquire=ref(false);
const form = reactive({
	agreement:false,
	pay_type: '',
	type: 'reservation',
	platform: '',
	technician_id: 0,
	address_id: 0,
	service: [],
	scheduling_id: 0,
	servive_time: '',
	remark: '',
	code: '',
	to_shop: 0,
	travel: {
		type: '',
		id: '',
		name: '',
		start_distance: 0,
		start_price: 0,
		mileage_price: 0,
		virtually_mileage: 0,
		commuting: 0
	},
	coupon: []
});
const coupon = ref([]);
const distance = ref(12000);
const travels = ref([]);
const travelShow = ref(false);//出行方式弹出层
const serviceTimeShow = ref(false);//服务时间弹出层
const payTypeShow = ref(false);//支付方式弹出层
const couponShow = ref(false);//优惠券弹出层
const price = computed(() => {
	let price = 0;
	let basic_price = 0;
	let overtime_price = 0;
	for (let i = 0; i < projects.value.length; i++) {
		const item = projects.value[i];
		let p = 0;
		let num = item.num;
		price += +item.price;
		basic_price += +item.price;
		num--;
		if (num > 0) {
			if (item.overtime_separate) {
				p = +item.overtime_price * num;
			} else {
				p = +item.price * num;
			}
		}
		overtime_price += p;
		price += p;
	}
	return { price: +price.toFixed(2), basic_price: +basic_price.toFixed(2), overtime_price: +overtime_price.toFixed(2) };
});
const price_sum = computed(() => {
	return +(price.value.price + travel.value.price - coupon_price.value).toFixed(2);
});
const service_duration = computed(() => {
	let service_duration = 0;
	let basic_duration = 0;
	let overtime_duration = 0;
	for (let i = 0; i < projects.value.length; i++) {
		const item = projects.value[i];
		let duration = 0;
		let num = item.num;
		service_duration += item.service_duration;
		basic_duration += item.service_duration;
		num--;
		if (num > 0) {
			if (item.overtime_separate) {
				duration = item.overtime_duration * num;
			} else {
				duration = item.service_duration * num;
			}
		}
		service_duration += duration;
		overtime_duration += duration;
	}
	return { service_duration, basic_duration, overtime_duration };
});
const service_duration_sum = computed(() => {
	return service_duration.value.service_duration + travel.value.commuting;
});
const travel = computed(() => {
	let result = { text: '请先选择地址和服务时间', price: 0, commuting: 0, reach_time: '' };
	if(form.to_shop) return result;
	const travel = form.travel;
	if (travel.type) {
		let start_distance = travel.start_distance * 1000;
		let selfDistance = distance.value + distance.value * (travel.virtually_mileage / 100);
		let mileage = 0;
		let mileage_price = 0;
		let price = travel.start_price;
		if (start_distance > 0 && selfDistance > start_distance) {
			mileage = selfDistance - start_distance;
		}
		if (mileage > 0 && travel.mileage_price > 0) {
			mileage = Math.ceil(mileage / 1000);
			mileage_price = Number((mileage * travel.mileage_price).toFixed(2));
			price += +mileage_price;
		}
		result.text = `全程共${Math.ceil(selfDistance / 1000)}公里，${travel.name}收取来回车费，单程起步${travel.start_price}元/${travel.start_distance}公里。`;
		if (mileage > 0) {
			result.text += `超出${mileage}公里,每公里收取${travel.mileage_price}元,共计${mileage_price}元。`;
		}
		result.price = price * 2;
		result.commuting = travel.commuting * Math.ceil(selfDistance / 1000);
		result.text += `预计需要${result.commuting}分钟到达`;
		if (form.servive_time) {
			const today = new Date();
			const date = new Date(form.servive_time.replace(/-/g, '/'));
			date.setMinutes(date.getMinutes() + result.commuting);
			if (date.getDate() === today.getDate()) {
				result.reach_time = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
			} else {
				result.reach_time = `${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
			}
		}
	}
	result.price = +result.price.toFixed(2);
	return result;
});
const coupon_price = computed(() => {
	let price = 0;
	for (let i = 0; i < coupon.value.length; i++) {
		const item = coupon.value[i];
		price += +item.money;
	}
	price = +price.toFixed(2);
	return price;
});
const getAddress = () => {
	$api.Address.getAddressDetails('').then((data: any) => {
		address.value = data;
		form.address_id = data.id;
		getDistance();
		getTravel();
	}).catch(() => { }).finally(() => {
		loading.value = false;
	})
}
const getDistance = () => {
	$api.Technician.getDistance({
		address_id: form.address_id,
		technician_id: form.technician_id
	}).then((data: any) => {
		distance.value = data.distance;
	}).catch((err: any) => {
		$message.error(err.msg);
	})
}
const getTravel = () => {
	if (!address.value.city_id || !form.servive_time) return;
	$api.Travel.list({ city_id: address.value.city_id, servive_time: form.servive_time, technician_id: form.technician_id }).then((res: any) => {
		travels.value = res.data;
		pickerPopup(res.data[0]);
	}).catch(() => {
		pickerPopup({
			type: '',
			id: '',
			name: '',
			start_distance: 0,
			start_price: 0,
			mileage_price: 0,
			virtually_mileage: 0,
			commuting: 0
		});
	})
}
const showPay = () => {
	if (!form.address_id && !form.to_shop) {
		return uni.showModal({
			title: '提示',
			content: '还未选择地址，是否立即去选择？',
			confirmText: '去选择',
			success(res) {
				if (res.confirm) {
					$page.open('/pages/user/address/list?event=' + $EventName.SELECT_ADDRESS);
				}
			}
		});
	}
	if(!form.agreement){
		return showAgreement(showPay);
	}
	if (!form.scheduling_id) {
		return serviceTimeShow.value = true;
	}
	if (!form.travel.type && !form.to_shop) {
		return toChangeTravel();
	}
	payTypeShow.value = true;
}
const payCallBack = (pay_type?: string) => {
	if (pay_type) {
		form.pay_type = pay_type;
		form.service = projects.value.map((item: any) => {
			return {
				id: item.id,
				num: item.num
			}
		});
		if (orders.value.trade) {
			getPayInfo();
		} else {
			getOrdersInfo();
		}
	}
	payTypeShow.value = false;
}
const getPayInfo = () => {
	uni.showLoading({
		title: '获取订单中...',
		mask: true
	})
	$api.Orders.payByOrders({
		trade: orders.value.trade,
		platform: form.platform,
		pay_type: form.pay_type,
		code: form.code
	}).then((res: any) => {
		uni.hideLoading();
		if (res.data.order && res.data.order.trade) {
			orders.value = res.data.order
		}
		pay(res);
	}).catch((err: any) => {
		uni.hideLoading();
		$message.error(err.msg);
		if (err.data && err.data.trade) {
			orders.value = err.data
		} else {
			orders.value = {
				trade: '',
			};
		}
	})
}
const getOrdersInfo = () => {
	uni.showLoading({
		title: '获取订单中...',
		mask: true
	})
	$api.Orders.create(form).then((res: any) => {
		uni.hideLoading();
		if (res.data.order && res.data.order.trade) {
			orders.value = res.data.order
		}
		pay(res);
	}).catch((err: any) => {
		uni.hideLoading();
		$message.error(err.msg);
		if (err.data && err.data.trade) {
			orders.value = err.data
		}
	})
}
const pay = (res: any) => {
	if (res.code === $ResponseCode.SUCCESS) {
		nextTick(() => {
			uni.showLoading({
				title: '查询中...',
				mask: true
			});
			usePay(res.data).then(() => {
				uni.hideLoading();
				uni.$emit($EventName.UPDATE_ORDER);
				$api.User.userinfo(this, true);
				$page.redirect('/pages/order/payment?trade=' + res.data.order.trade)
			}).catch((err: any) => {
				uni.hideLoading();
				if (err && err.msg) {
					$message.error(err.msg);
				}
			});
		})
	} else if (res.code === $ResponseCode.PAY_SUCCESS) {
		uni.$emit($EventName.UPDATE_ORDER);
		$api.User.userinfo(this, true);
		$page.redirect('/pages/order/payment?trade=' + res.data.order.trade)
	}
}
const valChange = (num: any, index: number) => {
	const service = projects.value[index];
	if (num <= 0) {
		uni.showModal({
			title: '提示',
			content: `移除${service.title}服务？`,
			success: res => {
				if (res.confirm) {
					projects.value.splice(index, 1);
					nextTick(() => {
						ReservaData();
					})
					if (projects.value.length <= 0) {
						useStorage().remove('ReservaData');
						$page.back();
					}
				} else if (res.cancel) {
					service.num = 1;
				}
			}
		})
	} else {
		nextTick(() => {
			ReservaData();
		})
	}
}
const ReservaData = () => {
	let ReservaData = {
		technician: technicianInfo.value,
		service: projects.value.filter((item: any) => item.num > 0)
	};
	useStorage().set('ReservaData', ReservaData)
}
const serviceTimePopup = (data: any) => {
	form.scheduling_id = data.id;
	servive_time.value = data.servive_time;
	form.servive_time = data.start_time;
	getTravel();
}
const pickerPopup = (data: any) => {
	form.travel = data;
	cancelOrders();
}
const couponPopup = (data: any) => {
	if (data && data.ids) {
		form.coupon = data.ids;
		coupon.value = data.coupon;
		cancelOrders();
	} else {
		form.coupon = [];
		coupon.value = [];
	}
}
const toChangeTravel = () => {
	if (travels.value.length <= 0) return;
	travelShow.value = true;
}
const toSetCouponShow = () => {
	couponShow.value = true;
}
const cancelOrders = () => {
	if (orders.value.trade) {
		$api.Orders.cancel(orders.value.trade).then(() => {
			orders.value = {
				trade: '',
			}
		}).catch(() => { })
	}
}
let agreementFunc:Function|undefined;
const showAgreement=(func:Function)=>{
	agreement.value=true;
	if(func){
		agreementFunc=func;
	}
}
const hendleAgreement=(val:boolean)=>{
	agreement.value=false;
	form.agreement=val;
	if(agreementEnquire.value){
		useStorage().remove('OrderAgreement');
	}else{
		useStorage().set('OrderAgreement',true);
	}
	if(val&&agreementFunc){
		agreementFunc();
		agreementFunc=undefined;
	}
}
onLoad(() => {
	loading.value = true;
	form.platform = PLATFORM.value.platform;
	const ReservaData = useStorage().get('ReservaData');
	if (ReservaData) {
		projects.value = ReservaData.service;
		technicianInfo.value = ReservaData.technician;
		form.technician_id = ReservaData.technician.technician_id;
		// #ifdef MP-WEIXIN
		wx.login({
			success: (res: any) => {
				if (res.code) {
					form.code = res.code;
				}
			},
			fail: () => {
				uni.showModal({
					title: '提示',
					content: '微信授权失败',
					showCancel: false,
					success: (res) => {
						if (res.confirm) {
							$page.back();
						}
					}
				});
			}
		})
		// #endif
		getAddress();
	} else {
		loading.value = false;
		uni.showModal({
			title: '提示',
			content: '请先选择预约项目',
			showCancel: false,
			success: (res) => {
				if (res.confirm) {
					$page.back();
				}
			}
		});
	}
	const OrderAgreement=useStorage().get('OrderAgreement');
	if(OrderAgreement){
		form.agreement=true;
	}
	uni.$on($EventName.SELECT_ADDRESS, (res) => {
		address.value = res;
		form.address_id = res.id;
		getDistance();
		getTravel();
	})
})
onUnload(() => {
	uni.$off($EventName.SELECT_ADDRESS);
})
</script>

<style lang="scss" scoped></style>
